<template>
  <div>
    <a-card
      :bordered="false"
      :style="{marginTop: '20px'}"
      title="付款方式">
      <div class="table-operator">
        <a-row :gutter="24">
          <a-col :md="8">
            <a-button
              type="primary"
              icon="plus"
              v-if="planIncomeSave"
              @click="incomeAdd">新建</a-button>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-spin :spinning="loading">
          <a-table
            size="default"
            rowKey="incomeId"
            :columns="incomeExpensesColumns"
            :dataSource="incomes"
            :customRow="tableCustomRow"
            :pagination="false">
            <span
              slot="serial"
              slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span
              slot="action"
              slot-scope="text, record">
              <template>
                <a v-if="planIncomeUpdate" @click="handleEdit(record)">配置</a>
                <a-divider
                  v-if="!record.children"
                  type="vertical" />
                <a
                  v-if="!record.children && planIncomeDelete"
                  @click="handleDelete(record)">移除</a>
              </template>
            </span>
          </a-table>
        </a-spin>
      </div>
      <income-form
        ref="incomeModal"
        :visible="visible"
        :isEdit="isEdit"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
    <a-card
      :bordered="false"
      :style="{marginTop: '20px'}"
      title="附件"
      v-show="files">
      <a-button
        type="primary"
        icon="plus"
        @click="addFile">新建</a-button>
      <a-spin :spinning="fileTabLoading">
        <a-table
          size="default"
          rowKey="fileId"
          :columns="fileColumns"
          :style="{marginTop : '10px'}"
          :dataSource="files"
          :pagination="false">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="fileDownload"
            slot-scope="text, record">
            <a
              :href="`${record.fileUrl}`"
              :download="record.fileName">{{ record.fileName }}</a>
          </span>
          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a
                @click="handleShowImg(record)">预览</a>
              <a-divider type="vertical" />
              <a @click="handleDeteleFile(record)">删除</a>
            </template>
          </span>
        </a-table>
      </a-spin>
      <file-create-form
        ref="fileCreateForm"
        :visible="fileCreateVisible"
        @cancel="handleFileCancel"
        @ok="handleFileOK" />
    </a-card>
  </div>
</template>

<script>
// getGoodsList, saveGoods, updateGoods, deleteGoods
import { supplierInfo, getIncomeList, saveIncome, updateIncome, deleteIncomeReq, getFileByIds } from '@/api/manage'
import { incomeExpensesColumns, fileColumns } from '../config'
import { STable } from '@/components'
import IncomeForm from '@/views/contract/modules/IncomeForm'
import FileCreateForm from './FileCreateForm'
import { message, Modal } from 'ant-design-vue'
import { mapGetters } from 'vuex'
import { isInMenu } from '../../config'

export default {
  name: 'IncomeList',
  props: {
    contractInfo: {
      type: Object,
      default: null
    }
  },
  components: {
    STable,
    IncomeForm,
    FileCreateForm
  },
  data () {
    this.incomeExpensesColumns = incomeExpensesColumns
    this.fileColumns = fileColumns
    return {
      isAdd: false,
      isEdit: false,
      visible: false,
      loading: false,
      suppliers: undefined,
      confirmLoading: false,
      incomes: undefined,
      incomeRecord: undefined,
      income: undefined,
      // 附件
      files: undefined,
      fileTabLoading: false,
      fileCreateVisible: false,
      physicalSurveyCurrRowId: null
    }
  },
    computed: {
    ...mapGetters(['menu'])
  },
  created () {
    // 实际采购
    this.planIncomeSave = isInMenu(this.menu, 'ROLE_but:income:save')
    this.planIncomeUpdate = isInMenu(this.menu, 'ROLE_but:income:update')
    this.planIncomeDelete = isInMenu(this.menu, 'ROLE_but:income:delete')
  },
  mounted () {
    this.initIncomes()
    isInMenu(this.menu, 'ROLE_but:supplier:list') && supplierInfo({ page: 1, limit: 9999 }).then(res => {
      this.suppliers = res.data
    })
  },
  methods: {
    // 收支
    initIncomes () {
      this.loading = true
      const id = this.$route.query.contractId
      isInMenu(this.menu, 'ROLE_but:income:list') && getIncomeList({ contractId: id, page: 1, limit: 9999 }).then(res => {
        this.incomes = res.data
        this.loading = false
      })
    },
    incomeAdd () {
      this.visible = true
      this.isAdd = true
      this.isEdit = false
      this.$nextTick(() => {
        this.$refs.incomeModal.form.setFieldsValue({ contractName: this.contractInfo.contractName })
      })
    },
    handleEdit (record) {
      this.visible = true
      this.isEdit = true
      this.isAdd = false
      const form = this.$refs.incomeModal.form
      this.income = record
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    handleDelete (record) {
      Modal.confirm({
        title: '删除一级收支记录',
        content: '只允许删除一级收支记录且没有实际收支记录，删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.loading = true
          deleteIncomeReq({ incomeId: record.incomeId }).then(() => {
            message.success('删除成功')
            this.initIncomes()
          })
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
      this.$refs.incomeModal.form.resetFields()
    },
    handleOk () {
      const form = this.$refs.incomeModal.form
      this.confirmLoading = true
      const contractId = this.$route.query.contractId
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.payMoment instanceof Array && values.payMoment.length > 1) {
            this.$message.error('付款阶段只允许选一个')
            this.confirmLoading = false
            return null
          }
          if (values.payMoment instanceof Array) {
            values.payMoment = values.payMoment[0]
          }
          if (this.isAdd) {
            saveIncome(Object.assign({}, values, { contractId }))
              .then(() => {
                message.success('新增收支成功')
              })
              .finally(() => {
                this.visible = false
                this.confirmLoading = false
                this.initIncomes()
              })
          } else if (this.isEdit) {
            updateIncome(
              Object.assign({}, values, {
                contractId,
                incomeId: this.income.incomeId,
                fileIds: this.income.fileIds
              })
            )
              .then(res => {
                message.success('编辑收支成功')
              })
              .finally(() => {
                this.visible = false
                this.confirmLoading = false
                this.initIncomes()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 获取附件
    getFiles (record) {
      this.fileTabLoading = true
      if (record.fileIds) {
      getFileByIds({ fileIds: record.fileIds })
        .then(res => {
          if (res.data) {
            this.files = res.data
          } else {
            this.files = []
          }
        })
        .finally(() => {
          this.fileTabLoading = false
        })
      } else {
        this.fileTabLoading = false
        this.files = []
      }
    },
    handleFileCancel () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = false
    },
    addFile () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = true
    },
    handleDeteleFile (record) {
      let _fileIds = ''
      if (this.incomeRecord.fileIds) {
        const fids = this.incomeRecord.fileIds.split(',')
        const index = fids.indexOf(String(record.fileId))
        if (index > -1) {
          fids.splice(index, 1)
        }
        _fileIds = fids.join(',') || ''
        this.incomeRecord.fileIds = _fileIds
      }
      const params = {
        fileIds: _fileIds,
        incomeId: this.incomeRecord.incomeId,
        otherHandler: this.incomeRecord.otherHandler,
        ownerHandler: this.incomeRecord.ownerHandler,
        payMoment: this.incomeRecord.payMoment,
        amount: this.incomeRecord.amount,
        contractId: this.incomeRecord.contractId,
        bankName: this.incomeRecord.bankName,
        bankAccountName: this.incomeRecord.bankAccountName,
        bankAccount: this.incomeRecord.bankAccount
      }
      // 实际收支附件更改
      if (this.incomeRecord.parentId !== null) {
        updateIncome(params)
          .then(res => {
            this.getFiles({ fileIds: _fileIds })
            message.success('删除成功')
          })
          .finally(() => {
            this.fileCreateVisible = false
            this.incomeRecord.fileIds = _fileIds
            this.$refs.createModal.resetFileList()
          })
      } else {
        // 合同附件更改
        updateIncome(Object.assign(params, { parentId: this.incomeRecord.parentId }))
          .then(res => {
            this.getFiles({ fileIds: _fileIds })
            message.success('删除成功')
          })
          .finally(() => {
            this.fileCreateVisible = false
            this.$refs.createModal.resetFileList()
            this.incomeRecord.fileIds = _fileIds
            this.getFiles({ fileIds: _fileIds })
          })
      }
    },
    handleFileOK () {
      const form = this.$refs.fileCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors && values.fileIds) {
          const _fileIds = this.incomeRecord.fileIds ? this.incomeRecord.fileIds + ',' : ''
          const params = {
            fileIds: _fileIds + values.fileIds,
            incomeId: this.incomeRecord.incomeId,
            otherHandler: this.incomeRecord.otherHandler,
            ownerHandler: this.incomeRecord.ownerHandler,
            payMoment: this.incomeRecord.payMoment,
            amount: this.incomeRecord.amount,
            contractId: this.incomeRecord.contractId,
            bankName: this.incomeRecord.bankName,
            bankAccountName: this.incomeRecord.bankAccountName,
            bankAccount: this.incomeRecord.bankAccount
          }
          // 实际收支附件更改
          if (this.incomeRecord.parentId !== null) {
            updateIncome(params)
              .then(res => {
                this.getFiles({ fileIds: _fileIds + values.fileIds })
                message.success('新增成功')
              })
              .finally(() => {
                this.fileCreateVisible = false
                this.incomeRecord.fileIds = _fileIds + values.fileIds
                this.$refs.createModal.resetFileList()
              })
          } else {
            // 合同附件更改
            updateIncome(Object.assign(params, { parentId: this.incomeRecord.parentId }))
              .then(res => {
                this.getFiles({ fileIds: _fileIds + values.fileIds })
                message.success('新增成功')
              })
              .finally(() => {
                this.fileCreateVisible = false
                this.incomeRecord.fileIds = _fileIds + values.fileIds
                this.$refs.createModal.resetFileList()
              })
          }
        }
      })
    },
    tableCustomRow (record, index) {
      return {
                style: {
          'background-color': record.incomeId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.incomeId
            this.incomeRecord = record
            this.getFiles(record)
          }
        }
      }
    },
    handleShowImg (record) {
      this.$emit('handleShowImg', record)
    }
  }
}
</script>
